<template>
  <div>
    <div class="ldq-img-box">
      <input
        type="file"
        accept="image/*"
        multiple="multiple"
        id="xdaTanFileImg"
        @change="doUpload($event); $emit('input', files)" />
      <img class="upImg" src="./img/addp.png" />
    </div>
    <img
      class="addImg"
      v-for="(item, index) in imgs"
      :key="index"
      :src="item">
  </div>
</template>

<script>
export default {
  data () {
    return {
      files: [],
      imgs: []
    }
  },
  props: {
    maxLength: {
      type: [String, Number],
      default: 9
    }
  },
  created () {
    this.initParams()
  },
  methods: {
    initParams () {
      this.files = {}
    },
    getObjectURL (file) {
      var url = null
      if (window.createObjectURL!=undefined) { // basic
        url = window.createObjectURL(file)
      } else if (window.URL!=undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file)
      } else if (window.webkitURL!=undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file)
      }
      return url
    },
    doUpload (e) {
      this.files = []
      this.imgs = []
      if (e.target.files.length > this.maxLength) {
        this.$toast(`最多上传${this.maxLength}张图片`)
      }
      for (let key in e.target.files) {
        if (key < e.target.files.length && key < this.maxLength) {
          this.files.push(e.target.files[key])
          this.imgs.push(this.getObjectURL(e.target.files[key]))
        }
      }
    },
  },
}
</script>

<style lang='stylus' scoped>
  .ldq-img-box
    width 2.4rem
    height 2.4rem
    border 1px dashed #ccc
    position relative
    border-radius 5px
    box-sizing border-box
    display inline-block
    // &:hover
    //   border 1px dashed #409eff !important
    input
      width 100%
      height 100%
      opacity 0
      position absolute
      top 0
      left 0
      z-index 2
      cursor pointer
    img
      width 100%
      height 100%
      position absolute
      top 0
      left 0
      z-index 1
      cursor pointer
  .addImg
    width 2.4rem
    height 2.4rem
    border 1px dashed #ccc
    border-radius 5px

</style>
